from tronpy import Tron
from tronpy.keys import PrivateKey
from tronpy.exceptions import AddressNotFound
import os
import uuid
import time
from crudtool import GenericCrudTool

# 初始化 Tron 客户端
client = Tron()
tool=GenericCrudTool(host="127.0.0.1",user="root",password="root",db="coin_account")

def check_balance(private_key_str):
    # 替换为你的私钥
    # private_key_str = "967208da3a945152835838fa3d0c70ecb808fd2d932f3da0d16c16543f0aa3f1"
    private_key = PrivateKey(bytes.fromhex(private_key_str))

    # # 获取地址
    address = private_key.public_key.to_base58check_address()

    # address="TMMQNYWGzTKrWJQXeEWhS94PouesPt6Quz"
    # 查询 TRX 余额

    try:
        trx_balance = client.get_account_balance(address)
        return str(trx_balance),2,address
    except AddressNotFound:
        return "",-1,address
    except Exception as e:
        print(f"An error occurred: {e}")
        return "",0,""
    # # 查询 USDT 余额
    # contract_address = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"  # TRC20 USDT 合约地址
    # contract = client.get_contract(contract_address)

    # if contract:
    #     usdt_balance = contract.functions.balanceOf(address) / 1_000_000  # USDT 精度为 6
    #     print(f"USDT 余额: {usdt_balance} USDT")
    # else:
    #     print("无法找到 USDT 合约，请检查网络连接或合约地址是否正确。")

def make_address(private_key_str):
    private_key = PrivateKey(bytes.fromhex(private_key_str))
    # # 获取地址
    address = private_key.public_key.to_base58check_address()
    return address

def do_page(id):
    print(f"batchid:{id}")
    sql="select * from tb_tag where state=0 and id > %s limit 2 "
    dataItems=tool.execute_query(sql,(id,))
    result=[]
    if len( dataItems) ==0:
        return [],-1
    lastId=0
    for item in dataItems:
        private_key=item["private_key"]
        balance,flag,address=check_balance(private_key)
        print(f"balance:{balance},flag:{flag},address:{address}")
        if flag==2 or flag==-1:
            result.append({"id":item["id"],"balance_str":balance,"balance_flag":flag,"address":address,"state":1})
        lastId=item["id"]
        time.sleep(20)
    return result,lastId



def do_work():
    id=0
    result,lastId=do_page(id)
    if len(result)>0:
        tool.batch_update("tb_tag",result)
    id=lastId
    while True:
        if id==-1:
            break
        result,lastId=do_page(lastId)
        if len(result)>0:
            tool.batch_update("tb_tag",result)
        id=lastId
        time.sleep(1)

def make_address_page(id):
    print(f"batchid:{id}")
    sql="select * from tb_tag where state=0 and id > %s limit 10000 "
    dataItems=tool.execute_query(sql,(id,))
    result=[]
    if len( dataItems) ==0:
        return [],-1
    lastId=0
    for item in dataItems:
        private_key=item["private_key"]
        address=make_address(private_key)
        if address:
            result.append({"id":item["id"],"address":address,"state":1})
        lastId=item["id"]
    return result,lastId

def do_address_work():
    id=0
    result,lastId=make_address_page(id)
    if len(result)>0:
        tool.batch_update("tb_tag",result)
    id=lastId
    while True:
        if id==-1:
            break
        result,lastId=make_address_page(lastId)
        if len(result)>0:
            tool.batch_update("tb_tag",result)
        id=lastId
        print(f"lastId:{lastId}")



if __name__ == '__main__':
    do_address_work()
    print("finish")




